//基本配置
var database={
    data:{
        list:[
            {"s_table":"user_t","s_col":"s_no","s_cn":"工号","s_regex":"/^.{1,20}$/","s_attr":"primary key"},
            {"s_table":"user_t","s_col":"s_name","s_cn":"姓名","s_regex":"/^.{1,90}$/","s_attr":""},
        ],
        table:[]
    },
    tmp_table:"",
    tmp_arr:""
};

//事件
database.Show=function(){
    msgbox.Loading();
    m.request({
        method:"GET",
        url:"php/database.php?p=list&s_project_path="+index.rootpath+system.data.s_project_path
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database.data.list=res.list;
            m.render(document.querySelector(".content"),m(database));
        }else{
            msgbox.Error(res.message);
        }
    })
}

database.ShowAdd=function(){
    msgbox.Loading();
    m.request({
        method:"GET",
        url:"php/dictionary.php?p=list",
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database_add.dictionary=res.list;
            m.render(document.querySelector(".content"),m(database_add));
        }else{
            msgbox.Error(res.message);
        }
    })
}

database.ShowEdit=function(item){
    database_edit.data=item;
    msgbox.Loading();
    m.request({
        method:"GET",
        url:"php/dictionary.php?p=list",
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database_edit.dictionary=res.list;
            m.render(document.querySelector(".content"),m(database_edit));
        }else{
            msgbox.Error(res.message);
        }
    })
}

database.AddRow=function(){
    var tbl=document.querySelector(".page_content").querySelector("table");
    var tr=tbl.insertRow();
    // td1=tr.insertCell();
    td2=tr.insertCell();
    td3=tr.insertCell();
    td4=tr.insertCell();
    td5=tr.insertCell();
    td6=tr.insertCell();
    // td1.innerText=tbl.rows.length-1;
    td2.innerHTML='<input type="text" list="dic" onblur="database.GetDic(this)"/>';
    td3.innerHTML='<input type="text"/>';
    td4.innerHTML='<input type="text" list="types"/>';
    td5.innerHTML='<input type="text" list="attrs"/>';
    td6.innerHTML='<button onclick="database.DelRow(this)">删除</button>';
}
database.DelRow=function(e){
    e.parentNode.parentNode.remove();
}
database.GetDic=function(e){
    for(var i=0;i<database_add.dictionary.length;i++){
        if(e.value==database_add.dictionary[i].id){
            e.parentNode.parentNode.querySelectorAll("input")[0].value=database_add.dictionary[i].s_en;
            e.parentNode.parentNode.querySelectorAll("input")[1].value=database_add.dictionary[i].s_cn;
            // e.parentNode.parentNode.querySelectorAll("input")[2].value=database_add.dictionary[i].s_regex;
            e.parentNode.parentNode.querySelectorAll("input")[3].value="";
        }
    }
    for(var i=0;i<database_edit.dictionary.length;i++){
        if(e.value==database_edit.dictionary[i].id){
            e.parentNode.parentNode.querySelectorAll("input")[0].value=database_edit.dictionary[i].s_en;
            e.parentNode.parentNode.querySelectorAll("input")[1].value=database_edit.dictionary[i].s_cn;
            // e.parentNode.parentNode.querySelectorAll("input")[2].value=database_edit.dictionary[i].s_regex;
            e.parentNode.parentNode.querySelectorAll("input")[3].value="";
        }
    }
}

database.SubmitAdd=function(){
    if(!/^.{1,90}$/.test(document.querySelector("#s_table").value)){
        msgbox.Error("输入的表名格式错误");
        return;
    }
    var postData=new FormData();
    var tbl=document.querySelector(".page_content").querySelector("table");
    // console.log(tbl);
    for(var i=1; i<tbl.rows.length; i++){
        // console.log(tbl.rows[i]);
        // console.log(tbl.rows[i].cells[0].querySelector("input").value);

        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[0].value)){
            msgbox.Error("第"+i+"行,栏位输入格式错误");
            return;
        }
        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[1].value)){
            msgbox.Error("第"+i+"行,中文输入格式错误");
            return;
        }
        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[2].value)){
            msgbox.Error("第"+i+"行,约束输入格式错误");
            return;
        }
        if(!/^.{0,90}$/.test(tbl.rows[i].querySelectorAll("input")[3].value)){
            msgbox.Error("第"+i+"行,索引输入格式错误");
            return;
        }
        postData.append("s_table",document.querySelector("#s_table").value);
        postData.append("s_col[]",tbl.rows[i].querySelectorAll("input")[0].value);
        postData.append("s_cn[]",tbl.rows[i].querySelectorAll("input")[1].value);
        postData.append("s_regex[]",tbl.rows[i].querySelectorAll("input")[2].value);
        postData.append("s_attr[]",tbl.rows[i].querySelectorAll("input")[3].value);
    }
    postData.append("s_project_path",index.rootpath+system.data.s_project_path);
    msgbox.Loading();
    m.request({
        method:"POST",
        url:"php/database.php?p=add",
        body:postData
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database.Show();
        }else{
            msgbox.Error(res.message);
        }
    })
}
database.SubmitEdit=function(){
    if(!/^.{1,90}$/.test(document.querySelector("#s_table").value)){
        msgbox.Error("输入的表名格式错误");
        return;
    }
    var postData=new FormData();
    var tbl=document.querySelector(".page_content").querySelector("table");
    // console.log(tbl);
    for(var i=1; i<tbl.rows.length; i++){
        // console.log(tbl.rows[i]);

        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[0].value)){
            msgbox.Error("第"+i+"行,栏位输入格式错误");
            return;
        }
        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[1].value)){
            msgbox.Error("第"+i+"行,中文输入格式错误");
            return;
        }
        if(!/^.{1,90}$/.test(tbl.rows[i].querySelectorAll("input")[2].value)){
            msgbox.Error("第"+i+"行,约束输入格式错误");
            return;
        }
        if(!/^.{0,90}$/.test(tbl.rows[i].querySelectorAll("input")[3].value)){
            msgbox.Error("第"+i+"行,索引输入格式错误");
            return;
        }
        
        postData.append("s_col[]",tbl.rows[i].querySelectorAll("input")[0].value);
        postData.append("s_cn[]",tbl.rows[i].querySelectorAll("input")[1].value);
        postData.append("s_regex[]",tbl.rows[i].querySelectorAll("input")[2].value);
        postData.append("s_attr[]",tbl.rows[i].querySelectorAll("input")[3].value);
    }
    postData.append("s_table",document.querySelector("#s_table").value);
    postData.append("id",database_edit.data.id);
    postData.append("s_project_path",index.rootpath+system.data.s_project_path);
    msgbox.Loading();
    m.request({
        method:"POST",
        url:"php/database.php?p=edit",
        body:postData
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database.Show();
        }else{
            msgbox.Error(res.message);
        }
    })
}
database.SubmitDelete=function(){
    if(confirm("确定删除？")){
        var postData=new FormData();
        postData.append("id",database_edit.data.id);
        postData.append("s_project_path",index.rootpath+system.data.s_project_path);
        msgbox.Loading();
        m.request({
            method:"POST",
            url:"php/database.php?p=delete",
            body:postData
        }).then(function(res){
            msgbox.Hide();
            if(res.res=="OK"){
                database.Show();
            }else{
                msgbox.Error(res.message);
            }
        })
    }
}

database.Print=function(){
    
    window.onbeforeprint=function(){
        index.ShowPrint(system.data.s_project_name+"数据库",document.querySelector(".pdfs").outerHTML);
    }
    window.onafterprint=function(){
        index.HidePrint();
    }
    window.print();
}

database.ShowSave=function(){
    document.querySelector("dialog").setAttribute("style","width:300px; height:240px;");
    m.render(document.querySelector("dialog"),m(database_save));
    document.querySelector("dialog").showModal();
}
database.SubmitSave=function(){
    if(document.querySelector("#s_host").value=="" || 
        document.querySelector("#s_dbname").value=="" ||
        document.querySelector("#s_user").value=="" ||
        document.querySelector("#s_pwd").value==""
    ){
        msgbox.Error("数据库信息请输入完整");
        return;
    }
    var postData=new FormData();
    postData.append("s_host",document.querySelector("#s_host").value);
    postData.append("s_dbname",document.querySelector("#s_dbname").value);
    postData.append("s_user",document.querySelector("#s_user").value);
    postData.append("s_pwd",document.querySelector("#s_pwd").value);
    postData.append("s_project_path",index.rootpath+system.data.s_project_path);
    msgbox.Loading();
    m.request({
        method:"POST",
        url:"php/database.php?p=save",
        body:postData
    }).then(function(res){
        msgbox.Hide();
        if(res.res=="OK"){
            database.Show();
        }else{
            msgbox.Error(res.message);
        }
    })
}




//UI
database.view=function(){
    return [
        m("div.page_title","数据库"),
        m("div.page_menu",[
            m("button",{onclick:database.ShowAdd},"新增表"),
            m("button",{onclick:database.Print},"打印"),
            m("button",{onclick:database.ShowSave},"写入DB"),
        ]),
        m("div.page_content.page_content2",m("div.pdfs",[
            database.data.list.map((item)=>{
                if(item.i_drop==1) return;
                return m("table.pdftable",[
                    m("caption",[m("a",{href:"#",onclick:function(){
                        database.ShowEdit(item);
                    }},"表名："+item.s_table)]),
                    m("tr",[
                        m("th","序号"),
                        m("th","栏位"),
                        m("th","中文"),
                        m("th","约束"),
                        m("th","索引")
                    ]),
                    item.rows.map((row,index)=>{
                       return  m("tr",[
                            m("td",index+1),
                            m("td",row.s_col),
                            m("td",row.s_cn),
                            m("td",row.s_regex),
                            m("td",row.s_attr)
                        ]);
                    })
                ])
            })
        ]))
    ]
}


var database_add={
    database:[],
    dictionary:[]
}
database_add.view=function(){
    return [
        m("div.page_title","【新增】表"),
        m("div.page_menu",[
            m("button",{onclick:database.Show},"返回"),
            m("button",{onclick:database.AddRow},"新增一行")
        ]),
        m("div.page_content",[
            m("div.page_line",[
                m("div.page_tag","* 表名"),
                m("input[type=text].page_input#s_table")
            ]),
            m("div.page_line_br"),
            m("table",[
                m("tr",[
                    m("th","栏位"),
                    m("th","中文"),
                    m("th","约束"),
                    m("th","索引"),
                    m("th","操作")
                ])
            ]),
            m("datalist#dic",database_add.dictionary.map(op=>{
                return m("option",{value:op.id},op.s_en)
            })),
            m("datalist#types",[
                m("option",{value:"TINYINT"}),
                m("option",{value:"SMALLINT"}),
                m("option",{value:"MEDIUMINT"}),
                m("option",{value:"INT"}),
                m("option",{value:"BIGINT"}),
                m("option",{value:"FLOAT"}),
                m("option",{value:"DOUBLE"}),
                m("option",{value:"DECIMAL"}),
                m("option",{value:"DATETIME"}),
                m("option",{value:"TIME"}),
                m("option",{value:"YEAR"}),
                m("option",{value:"TIMESTAMP"}),
                m("option",{value:"TEXT"}),
                m("option",{value:"BLOB"}),
                m("option",{value:"MEDIUMBLOB"}),
                m("option",{value:"MEDIUMTEXT"}),
                m("option",{value:"LONGBLOB"}),
                m("option",{value:"LONGTEXT"}),
                m("option",{value:"TINYBLOB"}),
                m("option",{value:"TINYTEXT"})
            ]),
            m("datalist#attrs",[
                m("option",{value:"UNIQUE"}),
                m("option",{value:"PRIMARY KEY"}),
                m("option",{value:"PRIMARY KEY AUTO_INCREMENT"}),
                m("option",{value:"INDEX"}),
                m("option",{value:"FULLTEXT"})
            ])
        ]),
        m("div.page_foot",[
            m("button",{onclick:database.SubmitAdd},"保存")
        ])
    ]
}

var database_edit={
    database:[],
    dictionary:[],
    data:{}
}
database_edit.view=function(){
    return [
        m("div.page_title","【更新】表"),
        m("div.page_menu",[
            m("button",{onclick:database.Show},"返回"),
            m("button",{onclick:database.AddRow},"新增一行")
        ]),
        m("div.page_content",[
            m("div.page_line",[
                m("div.page_tag","* 表名"),
                m("input[type=text].page_input#s_table",{value:database_edit.data.s_table})
            ]),
            m("div.page_line_br"),
            m("table",[
                m("tr",[
                    m("th","栏位"),
                    m("th","中文"),
                    m("th","约束"),
                    m("th","索引"),
                    m("th","操作")
                ]),
                m("tbody",
                    database_edit.data.rows.map((item,index)=>{
                        return m("tr",[
                            m("td",m("input[type=text]",{list:"dic",value:item.s_col})),
                            m("td",m("input[type=text]",{value:item.s_cn})),
                            m("td",m("input[type=text]",{list:"types",value:item.s_regex})),
                            m("td",m("input[type=text]",{list:"attrs",value:item.s_attr})),
                            m("td",[
                                m("button",{onclick:function(){
                                    database.DelRow(this);
                                }},"删除"),
                                m("button",{onclick:function(){
                                    database.UpTr(index,database_edit.data.rows)
                                }},"上移"),
                                m("button",{onclick:function(){
                                    database.DownTr(index,database_edit.data.rows)
                                }},"下移")
                            ])
                        ])
                    })
                )
            ]),
            m("datalist#dic",database_edit.dictionary.map(op=>{
                return m("option",{value:op.id},op.s_en)
            })),
            m("datalist#types",[
                m("option",{value:"TINYINT"}),
                m("option",{value:"SMALLINT"}),
                m("option",{value:"MEDIUMINT"}),
                m("option",{value:"INT"}),
                m("option",{value:"BIGINT"}),
                m("option",{value:"FLOAT"}),
                m("option",{value:"DOUBLE"}),
                m("option",{value:"DECIMAL"}),
                m("option",{value:"DATETIME"}),
                m("option",{value:"TIME"}),
                m("option",{value:"YEAR"}),
                m("option",{value:"TIMESTAMP"}),
                m("option",{value:"TEXT"}),
                m("option",{value:"BLOB"}),
                m("option",{value:"MEDIUMBLOB"}),
                m("option",{value:"MEDIUMTEXT"}),
                m("option",{value:"LONGBLOB"}),
                m("option",{value:"LONGTEXT"}),
                m("option",{value:"TINYBLOB"}),
                m("option",{value:"TINYTEXT"})
            ]),
            m("datalist#attrs",[
                m("option",{value:"UNIQUE"}),
                m("option",{value:"PRIMARY KEY"}),
                m("option",{value:"PRIMARY KEY AUTO_INCREMENT"}),
                m("option",{value:"INDEX"}),
                m("option",{value:"FULLTEXT"})
            ])
        ]),
        m("div.page_foot",[
            m("button",{onclick:database.SubmitEdit},"保存"),
            m("button",{onclick:database.SubmitDelete},"删除")
        ])
    ]
}

database.UpTr=function(num,data){
    var tbody=document.querySelector(".page_content").querySelector("tbody");
    if(num==0){
        msgbox.Error("已经是第一行");
        return;
    }
    // console.log(data);
    var tmp=data[num-1];
    data[num-1]=data[num];
    data[num]=tmp;
    // console.log(data);return;
    m.render(tbody,data.map((item,index)=>{
        return m("tr",[
            m("td",m("input[type=text]",{list:"dic",value:item.s_col})),
            m("td",m("input[type=text]",{value:item.s_cn})),
            m("td",m("input[type=text]",{list:"types",value:item.s_regex})),
            m("td",m("input[type=text]",{list:"attrs",value:item.s_attr})),
            m("td",[
                m("button",{onclick:function(){
                    database.DelRow(this);
                }},"删除"),
                m("button",{onclick:function(){
                    database.UpTr(index,data)
                }},"上移"),
                m("button",{onclick:function(){
                    database.DownTr(index,data)
                }},"下移")
            ])
        ])
    }));
}

database.DownTr=function(num,data){
    var tbody=document.querySelector(".page_content").querySelector("tbody");
    if(num==data.length-1){
        msgbox.Error("已经是最后一行");
        return;
    }
    // console.log(data);
    var tmp=data[num+1];
    data[num+1]=data[num];
    data[num]=tmp;
    // console.log(data);return;
    m.render(tbody,data.map((item,index)=>{
        return m("tr",[
            m("td",m("input[type=text]",{list:"dic",value:item.s_col})),
            m("td",m("input[type=text]",{value:item.s_cn})),
            m("td",m("input[type=text]",{list:"types",value:item.s_regex})),
            m("td",m("input[type=text]",{list:"attrs",value:item.s_attr})),
            m("td",[
                m("button",{onclick:function(){
                    database.DelRow(this);
                }},"删除"),
                m("button",{onclick:function(){
                    database.UpTr(index,data)
                }},"上移"),
                m("button",{},"下移")
            ])
        ])
    }));
}

var database_save={};
database_save.view=function(){
    return [
        m("div.dialog_title","执行表覆盖，谨慎操作"),
        m("div.dialog_line",[
            m("div.dialog_tag","HOST"),
            m("input[type=text].dialog_input#s_host")
        ]),
        m("div.dialog_line",[
            m("div.dialog_tag","DBNAME"),
            m("input[type=text].dialog_input#s_dbname")
        ]),
        m("div.dialog_line",[
            m("div.dialog_tag","USER"),
            m("input[type=text].dialog_input#s_user")
        ]),
        m("div.dialog_line",[
            m("div.dialog_tag","PWD"),
            m("input[type=password].dialog_input#s_pwd")
        ]),
        m("div.dialog_bts",[
            m("button",{onclick:database.SubmitSave},"确定"),
            m("button",{onclick:msgbox.Hide},"取消")
        ])
    ]
}